//入口函数
$(function () {
  // 调接口 获取用户信息
  getUserInfo();
  //退出
  $("#btnLogout").on("click", function (e) {
    // alert(6);
    //当点击了退出按钮弹出一个遮罩层
    layer.confirm(
      "确定退出登录?",
      { icon: 3, title: "提示" },
      function (index) {
        //do something
        localStorage.clear();
        location.href = "/login.html";
        layer.close(index);
      }
    );
  });
});

function getUserInfo() {
  $.ajax({
    method: "get",
    url: "/my/userinfo",
    headers: {
      Authorization: localStorage.getItem("token") || "",
    },
    success: function (res) {
      // console.log(res);
      if (res.status !== 0) {
        return layui.layer.msg("获取用户信息失败！");
      }
      // 获取成功 渲染用户头像
      renderAvatar(res.data);
    },
  });
}
//渲染用户头像
function renderAvatar(user) {
  var name = user.nickname || user.username;
  $("#welcome").html("欢迎&nbsp;&nbsp;" + name);
  if (user.user_pic !== null) {
    $(".layui-nav-img").attr("src", user.user_pic).show();
    $(".text-avatar").hide();
  } else {
    $(".layui-nav-img").hide();
    var first = name[0].toUpperCase();
    $(".text-avatar").html(first).show();
  }
}
